import 'dart:async';

import 'package:flutter/material.dart';
import 'package:x3_form_core/x3_form_core.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/x3_component_core.dart';

import 'components/advanced_filter_date_range.dart';
import 'components/advanced_filter_input_text.dart';
import 'components/advanced_filter_multi_choice.dart';
import 'components/advanced_filter_single_choice.dart';
import 'components/advanced_filter_input_text_range.dart';
import 'components/advanced_filter_choice_date_range.dart';

/// 分组高级筛选
class BaseGroupAdvancedFilter extends StatefulWidget {
  final List<String> groupTitleList;
  final List<BaseAdvancedFilterProvider> filterProviderList;
  final Function(Map<String, dynamic>) onComplete;

  const BaseGroupAdvancedFilter({Key key, @required this.groupTitleList, @required this.filterProviderList, @required this.onComplete})
      : assert(filterProviderList.length == groupTitleList.length),
        super(key: key);

  @override
  _BaseGroupAdvancedFilterState createState() => _BaseGroupAdvancedFilterState();
}

class _BaseGroupAdvancedFilterState extends State<BaseGroupAdvancedFilter> {
  List<BaseAdvancedFilterProvider> get providerList => widget.filterProviderList;
  StreamController _resetStreamController = StreamController<bool>.broadcast();

  @override
  void initState() {
    super.initState();
    setProviderResetStream();
  }

  @override
  void dispose() {
    super.dispose();
    _resetStreamController.close();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.filterProviderList.length == 0) return BaseEmptyComponent();
    return SafeArea(
      child: Container(
        padding: EdgeInsets.only(left: 16, right: 16, bottom: 8),
        child: DefaultTabController(
          length: widget.filterProviderList.length,
          child: Column(
            children: [
              buildBottomSheetHead(),
              Expanded(child: buildContent()),
              BaseBottomSheetButtonBar(cancelText: '重置', completeText: '确定', onComplete: _onComplete, onCancel: _onReSet),
            ],
          ),
        ),
      ),
    );
  }

  Widget buildBottomSheetHead() {
    return Container(
      color: Colors.white,
      margin: EdgeInsets.symmetric(vertical: 4),
      height: 40,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(child: buildTabBar()),
          SizedBox(),
          BaseCloseButton(onPress: () => {Navigator.of(context, rootNavigator: true).pop()}),
        ],
      ),
    );
  }

  Widget buildTabBar() {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        double itemWidth = constraints.maxWidth / 5;
        return SizedBox(
          height: 48,
          child: TabBar(
            isScrollable: true,
            labelPadding: EdgeInsets.zero,
            tabs: widget.groupTitleList.map((e) => buildTabItem(title: e, itemWidth: itemWidth)).toList(),
          ),
        );
      },
    );
  }

  Widget buildTabItem({@required String title, @required double itemWidth}) {
    return Container(width: itemWidth, alignment: Alignment.center, child: Text(title));
  }

  Widget buildContent() {
    return TabBarView(children: widget.filterProviderList.map((e) => buildTabBarViewItem(e)).toList());
  }

  /// 构建内容
  Widget buildTabBarViewItem(BaseAdvancedFilterProvider provider) {
    return Provider(
      create: (_) => provider,
      child: Consumer<BaseAdvancedFilterProvider>(
        builder: (BuildContext context, BaseAdvancedFilterProvider model, Widget child) {
          return ListView.separated(
            itemCount: provider.models.length,
            separatorBuilder: (BuildContext context, int index) => SizedBox(height: 16, child: Divider(height: 1)),
            itemBuilder: (context, index) {
              return catalog(model.models[index]);
            },
          );
        },
      ),
    );
  }

  /// 完成
  void _onComplete() {
    Map<String, dynamic> completeStartMap = {};
    Map<String, dynamic> completeEndMap = {};

    providerList.forEach((provider) {
      completeStartMap.addAll(provider.getAllDataKeyMap());
    });

    completeStartMap.forEach((key, value) {
      if (value != null) completeEndMap.addAll({"$key": value});
    });

    completeEndMap.removeWhere((key, value) {
      return (value is List && value.length == 0) || (value.toString() == '-2') || (value is List && value.contains('-2'));
    });

    widget.onComplete(completeEndMap);
    Navigator.of(context).pop();
  }

  /// 重置
  void _onReSet() {
    this._resetStreamController.sink.add(true);
    providerList.forEach((provider) {
      provider.dataSource.clear();
    });
    // Navigator.of(context).pop();
  }

  /// 设置重置流
  void setProviderResetStream() {
    providerList.forEach((provider) {
      provider.resetStream = _resetStreamController.stream as Stream<bool>;
    });
  }

  /// 筛选目录
  Widget catalog(BaseAdvancedFilterModel model) {
    Map<BaseAdvancedFilterType, Widget> catalog = {
      BaseAdvancedFilterType.ChoiceDateRange: AdvancedFilterChoiceDateRange(model: model),
      BaseAdvancedFilterType.SingleChoice: AdvancedFilterSingleChoice(model: model),
      BaseAdvancedFilterType.MultipleChoice: AdvancedFilterMultiChoice(model: model),
      BaseAdvancedFilterType.InputDateRange: AdvancedFilterDateRange(model: model),
      BaseAdvancedFilterType.InputTextRange: AdvancedFilterInputTextRange(model: model),
      BaseAdvancedFilterType.InputNumRange: AdvancedFilterInputTextRange(model: model, keyboardType: TextInputType.numberWithOptions(decimal: true)),
      BaseAdvancedFilterType.InputText: AdvancedFilterInputText(model: model),
    };
    return catalog[model.inputType];
  }
}
